//
//  CrossSlipDetailViewController.m
//  shise
//
//  Created by 徐国庆 on 14/12/20.
//  Copyright (c) 2014年 MZP. All rights reserved.
//

#import "CrossSlipDetailViewController.h"
#import "CrossSlipDetailOneCell.h"
#import "NetHandler.h"
#import "Food.h"
#import "Scroll.h"
#import "UIImageView+WebCache.h"
#import "MoreDetailCell.h"
#import "DataBaseHaneler.h"
#import "FoodDetailViewController.h"
#import "MJRefresh.h"
#import "DetailViewController.h"
#import "UserDetailViewController.h"

@interface CrossSlipDetailViewController ()<UITableViewDataSource, UITableViewDelegate>

@property(nonatomic, retain)UITableView *tableView;
@property(nonatomic, retain)NSMutableArray *array;
@property(nonatomic, retain)NSMutableArray *arrayOfFood;
@property(nonatomic, retain)NSString *refresh;


@end

@implementation CrossSlipDetailViewController

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        
        self.array = [NSMutableArray array];
        self.arrayOfFood = [NSMutableArray array];
        
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.view.backgroundColor = [UIColor blackColor];
    self.tableView.backgroundColor = [UIColor blackColor];

    
    self.tableView = [[UITableView alloc] initWithFrame:self.view.bounds];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.view addSubview:self.tableView];
    [_tableView release];
    
//    [self handleData];
    [self setupRefresh];
    
    self.title = @"详情";
    
    
}

// 设置cell的个数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.array.count - 1;
}

// 设置cell 的内容
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    Scroll *scroll = [self.array objectAtIndex:indexPath.row];
    
    if ([scroll.type isEqualToString:@"EventCard"]) {
        
//        Scroll *scroll = [self.array objectAtIndex:indexPath.row];
        NSString *string = @"ss";
        CrossSlipDetailOneCell *cell = [tableView dequeueReusableCellWithIdentifier:string];
        if (cell == nil) {
            
            cell = [[[CrossSlipDetailOneCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:string]autorelease];
            
        }
        [cell.activityImageView setImageWithURL:[NSURL URLWithString:scroll.pic_url]];
        cell.activityName.text = scroll.title;
        cell.joinCount.text = scroll.desc;
        return cell;

        
    } else if([scroll.type isEqualToString:@"UserCard"]) {
        
//        Scroll *scroll = [self.array objectAtIndex:indexPath.row];
        
        NSString *string = @"aa";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:string];
        if (cell == nil) {
            
            cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:string]autorelease];
        }
        [cell.imageView setImageWithURL:[NSURL URLWithString:scroll.avatar]];
        cell.textLabel.text = scroll.title;
        cell.detailTextLabel.text = scroll.desc;
        return cell;
        
    } else if ([scroll.type isEqualToString:@"PicCard"]){
        
//        Scroll *scroll = [self.array objectAtIndex:indexPath.row];
        
        NSString *string = @"sa";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:string];
        if (cell == nil) {
            
            cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:string]autorelease];
            
        }
        cell.textLabel.text = scroll.desc;
        cell.textLabel.numberOfLines = 0;
        cell.textLabel.font = [UIFont systemFontOfSize:16];
        cell.textLabel.alpha = 0.8;
        [cell.textLabel sizeToFit];
        return cell;
    } else {
        Food *food = [self.arrayOfFood objectAtIndex:indexPath.row + 1];
        NSString *string = @"gg";
        MoreDetailCell *cell = [tableView dequeueReusableCellWithIdentifier:string];
        if (cell == nil) {
            
            cell = [[[MoreDetailCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:string]autorelease];
            
        }
        [cell.foodImageView setImageWithURL:[NSURL URLWithString:food.pic_url]];
        [cell.userHeadImageView setImageWithURL:[NSURL URLWithString:[food.user objectForKey:@"avatar"]]];
        cell.userName.text = food.userName;
        cell.userAddress.text = food.location;
        cell.userSay.text = food.content;
        if (food.content.length == 0) {
            
            cell.userSay.numberOfLines = 0;
            
        } else if (food.content.length < 20) {
            
            cell.userSay.numberOfLines = 1;
        } else {
            
            cell.userSay.numberOfLines = 2;
        }
        if (food.clickPraiseCount % 2 == 0) {
            
            cell.praiseImageView.image = [UIImage imageNamed:@"praiseFont.png"];
        } else {
            
            cell.praiseImageView.image = [UIImage imageNamed:@"praiseBehind.png"];
        }
        
        cell.praise.text = @"赞";
        cell.praiseNumbers.text = food.likeCount;
        if (food.clickMarkCount != 0) {
            
            cell.markImageView.image = [UIImage imageNamed:@"markBehind.png"];
        } else {
            
            cell.markImageView.image = [UIImage imageNamed:@"mark.png"];
        }
        cell.mark.text = @"马克";
        // 设置tag值用来判断点击的图片是第几个cell上的
        // 美食图片tag值1000+
        cell.foodImageViewButton.tag = 1000 + indexPath.row + 1;
        // 用户头像tag值2000+
        cell.userHeadImageViewButton.tag = 2000 + indexPath.row + 1;
        // 赞图片tag值3000 +
        cell.praiseImageViewButton.tag = 3000 + indexPath.row + 1;
        // 马克图片tag值4000 +
        cell.markImagViewButton.tag = 4000 + indexPath.row + 1;
        // 设置点击美食图片按钮方法
        [cell.foodImageViewButton addTarget:self action:@selector(foodImageViewButtonAction:) forControlEvents:UIControlEventTouchUpInside];
        // 设置点击头像图片按钮方法
        [cell.userHeadImageViewButton addTarget:self action:@selector(userHeadImagViewButtonAction:) forControlEvents:UIControlEventTouchUpInside];
        // 设置点击赞图片按钮方法
        [cell.praiseImageViewButton addTarget:self action:@selector(praiseImageViewButtonAction:) forControlEvents:UIControlEventTouchUpInside];
        // 设置点击马克图片按钮方法
        [cell.markImagViewButton addTarget:self action:@selector(markImagViewButtonAction:) forControlEvents:UIControlEventTouchUpInside];
        return cell;
        
    }
}

// 自定义处理数据的方法
- (void)handleData
{
    NSString *string = [NSString stringWithFormat:@"https://api.shiseapp.com%@", self.address];
    NSLog(@"活动详情地址%@", string);
    [NetHandler getDataWithUrl:string completion:^(NSData *data) {
        
        NSError *error = nil;
        
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
        NSArray *arr = [dic objectForKey:@"data"];
        self.refresh = [[dic objectForKey:@"pagination"] objectForKey:@"nextUrl"];
//        NSLog(@"美食%@", self.refresh);

        [self.array removeAllObjects];
        [self.arrayOfFood removeAllObjects];
        for (NSDictionary *tempDic in arr) {
            Food *food = [[Food alloc] initWithDictionary:tempDic];
            Scroll *scroll = [[Scroll alloc] initWithDictionary:tempDic];
            [self.array addObject:scroll];
            [self.arrayOfFood addObject:food];
            [scroll release];
            [food release];
        }
        [self.tableView reloadData];
    }];
}

// 设置cell的高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    Scroll *scroll = [self.array objectAtIndex:indexPath.row];
    if ([scroll.type isEqualToString:@"EventCard"]) {
        return 150;
    } else if ([scroll.type isEqualToString:@"UserCard"]) {
        
        return 50;
    } else if ([scroll.type isEqualToString:@"PicCard"]) {
        
//        NSString *string = [[self.array objectAtIndex:indexPath.row].desc];
        Scroll *scroll = [self.array objectAtIndex:indexPath.row];
        NSString *string = scroll.desc;
//        NSLog(@"活动%@", string);
        NSDictionary *dic = @{NSFontAttributeName:[UIFont systemFontOfSize:16]};
        CGRect rect = [string boundingRectWithSize:CGSizeMake(self.tableView.frame.size.width, 10000) options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil];
        return rect.size.height + 80;
    } else {
//        Food *food = [self.arrayOfFood objectAtIndex:indexPath.row ];
//        
//        if (food.content.length == 0) {
//            
//            return 370;
//        } else if (food.content.length <= 20) {
//            
//            return 390;
//        } else {
//            return 420;
//        }
        return 410;
    }
}

// 点击cell的时候执行的方法
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    Scroll *scroll = [self.array objectAtIndex:indexPath.row];
    if ([scroll.type isEqualToString:@"UserCard"]) {
        
        Scroll *scroll = [self.array objectAtIndex:indexPath.row];
        UserDetailViewController *userDetailVC = [[UserDetailViewController alloc] init];
        userDetailVC.userApi = scroll.userId;
        [self.navigationController pushViewController:userDetailVC animated:YES];
        [userDetailVC release];
        
    }
}

// 点击美食图片上得按钮的时候执行这个方法
- (void)foodImageViewButtonAction:(UIButton *)button
{
//    NSLog(@"tag值%ld", button.tag);
    
    Food *food = [self.arrayOfFood objectAtIndex:button.tag - 1000];
    
    DetailViewController *detailVC = [[DetailViewController alloc] init];
    detailVC.detailApi = food.objId;
    [self.navigationController pushViewController:detailVC animated:YES];
    [detailVC release];
    
//    FoodDetailViewController *foodDetailVC = [[FoodDetailViewController alloc] init];
//    foodDetailVC.foodApi = food.objId;
//    
//    [self.navigationController pushViewController:foodDetailVC animated:YES];
//    [foodDetailVC release];
    // 可以根据tag值算出该按钮下得cell上得数据是数组中的第几个元素
    
}

// 点击用户头像的时候执行这个方法
- (void)userHeadImagViewButtonAction:(UIButton *)button
{
    Food *food = [self.arrayOfFood objectAtIndex:button.tag - 2000];
    NSDictionary *tempDic = food.user;
    NSString *tempString = [tempDic objectForKey:@"id"];
    UserDetailViewController *userDetailVC = [[UserDetailViewController alloc] init];
    userDetailVC.userApi = tempString;
    [self.navigationController pushViewController:userDetailVC animated:YES];
    [userDetailVC release];
    
}

// 点击“赞”的时候执行的方法
- (void)praiseImageViewButtonAction:(UIButton *)button
{
    
    // 当点击赞的时候赞的图片变成红色的同时赞的人数加1
    NSInteger numberOfCell = button.tag - 3000;
    Food *food = [self.arrayOfFood objectAtIndex:numberOfCell];
    if (food.clickPraiseCount % 2 == 0) {
        
        food.clickPraiseCount += 1;
        
        NSString *likeCount = food.likeCount;
        NSInteger likeCountNew = [likeCount integerValue];
        likeCountNew = likeCountNew + 1;
        //    NSNumber *num = [likeCount description];
        food.likeCount = [NSString stringWithFormat:@"%ld", (long)likeCountNew];
        //        self.number = 1;
        [self.tableView reloadData];
        
    } else {
        
        food.clickPraiseCount += 1;
        
        NSString *likeCount = food.likeCount;
        NSInteger likeCountNew = [likeCount integerValue];
        likeCountNew = likeCountNew - 1;
        //    NSNumber *num = [likeCount description];
        food.likeCount = [NSString stringWithFormat:@"%ld", (long)likeCountNew];
//        self.number = 1;
        [self.tableView reloadData];
    }
}

// 点击“马克”的时候执行的方法
- (void)markImagViewButtonAction:(UIButton *)button
{
    NSUserDefaults *def = [NSUserDefaults standardUserDefaults];
    if ([def objectForKey:@"userName"] == nil) {
        
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"请先登录" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
        [alertView show];

    } else {
        
        NSInteger numberOfCell = button.tag - 4000;
        Food *food = [self.arrayOfFood objectAtIndex:numberOfCell];
        food.clickMarkCount += 1;
        [self.tableView reloadData];
        // 当收藏本条美食信息的时候就讲本条没事信息存储到本地 当点击我的收藏的时候从本地读取信息 并显示
        DataBaseHaneler *handler = [DataBaseHaneler shareInstance];
        // 打开数据库
        [handler openDB];
        // 创建美食表表
        [handler createFoodTable];
        // 添加一条美食数据
        [handler insertFood:food userName:[def objectForKey:@"userName"]];
        
    }
    
    
}

- (void)setupRefresh
{
//    [self handleData];
    // 1.下拉刷新(进入刷新状态就会调用self的headerRereshing)
    [self.tableView addHeaderWithTarget:self action:@selector(headerRereshing)];
// warning 自动刷新(一进入程序就下拉刷新)
    [self.tableView headerBeginRefreshing];
    
    // 2.上拉加载更多(进入刷新状态就会调用self的footerRereshing)
    [self.tableView addFooterWithTarget:self action:@selector(footerRereshing)];
    
    // 设置文字(也可以不设置,默认的文字在MJRefreshConst中修改)
    self.tableView.headerPullToRefreshText = @"下拉可以刷新";
    self.tableView.headerReleaseToRefreshText = @"松开马上刷新";
    self.tableView.headerRefreshingText = @"正在刷新...";
    
    self.tableView.footerPullToRefreshText = @"上拉可以加载更多数据";
    self.tableView.footerReleaseToRefreshText = @"松开马上加载更多数据";
    self.tableView.footerRefreshingText = @"正在刷新...";
    
}

- (void)headerRereshing
{
    //    NSMutableArray *tempArr = [NSMutableArray arrayWithArray:self.foodArr];
    ////    [self.foodArr removeAllObjects];
    //
    //    NSString *str = @"https://api.shiseapp.com/v2/timeline/";
    //    [NetHandler getDataWithUrl:str completion:^(NSData *data) {
    //        NSError *resultError = nil;
    //        NSDictionary *result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&resultError];
    //
    //        NSArray *arr = [result objectForKey:@"data"];
    
    //    [self.array removeAllObjects];
    [self handleData];
    
    
    // 2.2秒后刷新表格UI
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        // 刷新表格
        [self.tableView reloadData];
        
        // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
        [self.tableView headerEndRefreshing];
    });
    //        }];
}


- (void)footerRereshing
{
//    [self handleData];
    [NetHandler getDataWithUrl:self.refresh completion:^(NSData *data) {
        NSError *resultError = nil;
        NSDictionary *result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&resultError];
        
        NSArray *arr = [result objectForKey:@"data"];
        self.refresh = [[result objectForKey:@"pagination"] objectForKey:@"nextUrl"];
//        NSLog(@"********%@", self.refresh);
        
        // 新建一个数组用来存放上拉刷新后 请求的美食对象
        NSMutableArray *newFoodArr = [NSMutableArray array];
        NSMutableArray *newScrollArr = [NSMutableArray array];
        for (NSDictionary *dic in arr) {
            Scroll *scroll = [[Scroll alloc] initWithDictionary:dic];
            Food *food = [[Food alloc] initWithDictionary:dic];
            [newFoodArr addObject:food];
            [newScrollArr addObject:scroll];
            [scroll release];
            [food release];
        }
        [self.array addObjectsFromArray:newScrollArr];
        [self.arrayOfFood addObjectsFromArray:newFoodArr];
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            // 刷新表格
            [self.tableView reloadData];
            
            // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
            [self.tableView footerEndRefreshing];
        });
        
    }];
    
}



- (void)dealloc
{
    [_address release];
    [_tableView release];
    [_array release];
    [_arrayOfFood release];
    [_refresh release];
    [super dealloc];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
